BaseController = RouteController.extend({
	layoutTemplate: "Layout",
	loadingTemplate: 'Loading',
	yieldRegions: {
		'Header': { to: 'header' }
	},
	apiServer: __meteor_runtime_config__.API_HOST,
	apiVersion: 'v2',
	mainView: '',
	center: '',
	left: '',
	right: '',
	transparent: false,
	eventMap: {},
	app: null,
	$$: '',
	apiKey: '9mF/KQGoPKnbGOFbUOJ661EJ8aLNTuDW',
	apiSecret: '95D47EAD959mF/KQGoPKnbGOFbUOJ661EJ8aLNTuDW8FHY=85F8A2CD193E2300F',
	subscribeHandleDict: [],
	curUser: {},
	currentUserData: new ReactiveVar(null),
	subscribeCallbacks: function () {
		let self = this;
		return {
			onReady: function () {
				self.onReadyCallBack();
				return self.ready();
			},
			onStop: function () {
				self.onStopCallBack();
				self.subscribeHandle();
			}
		}
	},
	onReadyCallBack: function () {

	},
	onStopCallBack: function () {

	},
	subscribeHandle: function () {

	},
	events: function () {
		return {};
	},
	accessToken: function () {
		Meteor.subscribe('accessTokens', {}, function () {
			//this.stop();
		});
	},
	on: function (event, callback) {
		let self = this;
		if (!self.eventMap[event]) {
			self.eventMap[event] = {};
		}
		if (!self.eventMap[event]['callbacks']) {
			self.eventMap[event]['callbacks'] = {};
		}
		self.eventMap[event]['callbacks'][CryptoJS.MD5(callback.toString()).toString()] = callback;
		$(document).on(event, function (evt) {
			$.each(self.eventMap[event]['callbacks'], function (idx, func) {
				func({
					event: evt,
					data: self.eventMap[event]['data']
				});
			});
		});
	},
	off: function (event, callback) {
		if (arguments.length == 2) {
			let key = CryptoJS.MD5(callback.toString()).toString();
			delete self.eventMap[event]['callbacks'][key];
		} else {
			delete self.eventMap[event];
		}
	},
	emit: function (event, params) {
		if (!this.eventMap[event]) {
			this.eventMap[event] = {};
		}
		this.eventMap[event]['data'] = params;
		$(document).trigger(event);
	},
	routeParam: function (key) {
		return this.params[key];
	},
	query: function (key) {
		return this.params.query[key];
	},
	checkLogin: function () {

	},
	platform: function () {
		return window.platform();
	},
	now: function () {
		return (new Date()).getTime();
	},
	loginToken: function () {
		let self = this;
		let now = this.now() / 1000;
		let selector = {
			'$or': [
				{
					'ttl': {
						'$gt': now
					}
				},
				{
					'refresh_ttl': {
						'$gt': now
					}
				}
			],
			token: localStorage.token
		};
		Meteor.subscribe('loginTokens', selector, { limit: 1 }, function () {
			if (this.ready) {
				let token = LoginToken.findOne();
				if (!token) {
					delete localStorage.token;
				} else {
					self.getCurrentUser();
				}
			}

		});
	},
	buildQuery: function (query, key) {
		let self = this;
		let queryStr = ''
		if (_.isString(query) || _.isNumber(query) || _.isNull(query)) {
			queryStr = !!key ? (key + '=' + query) : query;
		} else {
			if (_.isObject(query)) {
				_.each(query, function (val, index) {
					let tmp = '';
					if (key) {
						tmp += '[' + index + ']';
					} else {
						tmp = index;
					}
					queryStr += '&' + self.buildQuery(val, tmp);
				});
			} else {
				queryStr = '';
			}
		}
		return queryStr;
	},
	get: function (url, query) {
		let self = this;
		query = self.buildQuery(query, '');
		if (query) {
			query = '?' + query.substr(1);
		}
		return new Promise(function (resolve, reject) {
			HTTP.get(self.apiServer + "/" + self.apiVersion + "/" + url + query, function (error, result) {
				if (error) {
					reject(error);
				} else {
					resolve(result);
				}
			});
		});
	},
	post: function (url, data) {
		let self = this;
		return new Promise(function (resolve, reject) {
			HTTP.post(self.apiServer + "/" + self.apiVersion + "/" + url, {
				data: data
			}, function (error, result) {
				if (error) {
					reject(error);
				} else {
					resolve(result);
				}
			});
		});
	},
	put: function (url, data, callback) {
		let self = this;
		return new Promise(function (resolve, reject) {
			HTTP.put(self.apiServer + "/" + self.apiVersion + "/" + url, {
				data: data
			}, function (error, result) {
				if (error) {
					reject(error);
				} else {
					resolve(result);
				}
			});
		});
	},
	delete: function (id, callback) {
		let self = this;
		return new Promise(function (resolve, reject) {
			HTTP.del(self.apiServer + "/" + self.apiVersion + "/" + url, function (error, result) {
				if (error) {
					reject(error);
				} else {
					resolve(result);
				}
			});
		});
	},
	onBeforeAction: function () {
		if (!window.app) {
			window.app = new Framework7({
				pushState: true,
				swipePanel: 'left',
				modalTitle: "提示",
				modalButtonOk: "确定",
				modalButtonCancel: "取消",
			});
		}
		this.app = window.app;
		if (!window.$$) {
			window.$$ = Dom7;
		}
		this.$$ = window.$$;
		Template[this.template].onRendered(this.renderCallback);
		Template[this.template].events(this.events(this));
		let next = this.beforeAction();
		return !!next ? next() : '';
	},
	beforeAction: function () {
		return this.next;
	},
	renderCallback: function () {
		let controller = Iron.controller();
		//controller.emit('header.reset');
		if (Template.Header.url) Template.Header.url.set(controller.headerBack);
		if (Template.Header.center) Template.Header.center.set(Spacebars.SafeString(controller.center));
		if (Template.Header.left) Template.Header.left.set(Spacebars.SafeString(controller.left));
		if (Template.Header.right) Template.Header.right.set(Spacebars.SafeString(controller.right));
		let transparent = !!controller.headerTransparent ? 'transparent mask' : '';
		if (Template.Header.transparent) Template.Header.transparent.set(transparent);
		$('#views').removeAttr('class');
		$('#views').addClass("views " + controller.platform() + " " + controller.mainView);
		let self = this;
		//controller.location.configure({useHashPaths: true});
		controller.onRendered(controller);
	},
	onRendered: function (self) {
		// console.log('render template');
	},

	waitOn: function (){
		let meteor = '';

		meteor = this.accessToken();

		meteor = this.loginToken();

		return meteor;
	},
	wait: function () {
	},
	paging: function (collection_name, selector, sort, perpage, maxitem) {
		var myApp = new Framework7;
		var $$ = Dom7;
		var self = this;
		var loading = false;
		var perpages = perpage || 4;
		var maxItems = maxitem || 8;
		var sorts = sort || { id: -1 };
		var selectors = selector || {};
		var curlistLenght = 0;
		this.lastIndex = perpages || 10;
	
		$$('.infinite-scroll').on('infinite', function () {
			var listLenght = $$('.list-block li').length;
			if (listLenght > curlistLenght) {
				curlistLenght = listLenght;
			}
			if (loading) return;
			loading = true;
			setTimeout(function () {
				loading = false;
				if (self.lastIndex > curlistLenght) {
					//myApp.detachInfiniteScroll($$('.infinite-scroll'));
					$('.infinite-scroll-preloader').remove();
					return;
				}
				let subscribeName = collection_name.toString();
				self.lastIndex = self.lastIndex + perpages;
				if (typeof self.subscribeHandleDict[subscribeName] != 'undefined') {
					if (self.subscribeHandleDict[subscribeName]) {
						self.subscribeHandle = function () {
							self.subscribeHandleDict[subscribeName] = Meteor.subscribe(subscribeName, selectors, { sort: sorts, limit: self.lastIndex }, self.subscribeCallbacks());
						}
						self.subscribeHandleDict[subscribeName].stop();
					}
					return self.subscribeHandleDict[subscribeName];
				} else {
					return Meteor.subscribe(subscribeName, selectors, { sort: sorts, limit: self.lastIndex }, function () {
						return self.ready();
					});
				}
			}, 100)
		});
	},


	getDateStr: function (now, addDayCount) {
		now.setDate(now.getDate() + addDayCount);//获取AddDayCount天后的日期
		var y = now.getFullYear();
		var m = ("0" + (now.getMonth() + 1)).slice(-2);//获取当前月份的日期
		var d = ("0" + now.getDate()).slice(-2);
		now.setDate(now.getDate() - addDayCount);
		return y + "-" + m + "-" + d;
	},
	getRealTime: function (now, addDayCount) {
		var today = this.getDateStr(now, addDayCount);
		var hour = ("0" + now.getHours()).slice(-2);
		var minute = ("0" + now.getMinutes()).slice(-2);
		var second = ("0" + now.getSeconds()).slice(-2);
		return today + " " + (hour) + ":" + (minute) + ":" + (second);
	},
	getDateStart: function (now, addDayCount) {
		return this.getDateStr(now, addDayCount) + " 00:00:00";
	},
	currentUser: function () {
		return this.currentUserData ? this.currentUserData.get() : null;
	},
	userSubcribe: null,
	getCurrentUser() {
		let self = this;
		Meteor.call('auth', localStorage.token, function (error, result) {
			if (!error) {
				if (result && !self.userSubcribe) {
					self.userSubcribe = Meteor.subscribe('curUser', result, function () {
						self.curUser = Merchants.findOne({ id: result });
						self.currentUserData.set(self.curUser);
					});
				}
			}
		});
	},
	dateToTime(date) {
		var d = new Date(Date.parse(date.replace(/-/g, "/")));
		return d.getTime() / 1000;
	}
});
